/**
 * @Author Fizz Pu
 * @Date 2020/12/5 下午7:55
 * @Version 1.0
 * 失之毫厘，缪之千里！
 */
public class LeeOffer67 {
    public int strToInt(String str) {
        if(str == null || str.length() == 0)return 0;
        int charP = 0, len = str.length(), sums = 0;
        int flag = 1; // 默认为正数
        int isStackOverflow = 0;
        char curChar;

        // 去空格
        while (charP < len && str.charAt(charP) == ' '){charP++;}
        if(charP >= len){return 0;}  // 全为空

        // 判断正负
        curChar = str.charAt(charP);
        if(curChar == '-'){
            flag = -1;
            charP++;
        }
        if(curChar == '+'){
            charP++;
        }


        while (charP < len){
            curChar = str.charAt(charP++);
            if(curChar >= '0' && curChar <= '9'){
                // 处理溢出
                if(sums >= (Integer.MAX_VALUE - 9)/10){
                    isStackOverflow = 1;
                    break;
                }
                sums = sums * 10 + (curChar - '0');

            }
            else {break;}
        }

        if(isStackOverflow == 1 && flag == 1){
            return Integer.MAX_VALUE;
        }

        if(isStackOverflow == 1){
            return Integer.MIN_VALUE;
        }
        return flag * sums;
    }

    public static void main(String[] args) {
        LeeOffer67 leeOffer67 = new LeeOffer67();

        System.out.println(leeOffer67.strToInt(null));
        System.out.println(leeOffer67.strToInt(" "));
        System.out.println(leeOffer67.strToInt("41"));
        System.out.println(leeOffer67.strToInt("-41"));
        System.out.println(leeOffer67.strToInt("+41"));
        System.out.println(leeOffer67.strToInt("+41i"));
        System.out.println(leeOffer67.strToInt("+41 89"));
        System.out.println(leeOffer67.strToInt("+00"));
        System.out.println(leeOffer67.strToInt("-0041"));
        System.out.println(leeOffer67.strToInt("-418949283427439247294729"));
        System.out.println(leeOffer67.strToInt("+418949283427439247294729"));
    }
}
